package com.hzit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzit.entity.User;
import com.hzit.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：在此完成数据的认证与授权
 */
@Component
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {
	@Autowired
	private IUserService userService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//1. 根据传入的用户名,查询用户对象
		User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
		//2. 如果不存在,就抛出异常
		if(user == null){
			throw new UsernameNotFoundException("用户名不存在!");
		}
		//3. 取得用户密码
		String password = user.getPassword();
		//4. 根据登录的用户名username,查询出此用户的权限列表
		List<String> authList = userService.findAuthorityByUsername(username);
		log.info("当前登录用户的权限列表:{}",authList);
		//5. 处理权限串
		String authoriesList = authList.toString().replace("[","").replace("]",""); // "student:create,student:update,student:delete"
		log.info("处理完的最终权限串:{}",authoriesList);
		//6. 构造权限列表
		Collection<? extends GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(authoriesList);
		//7. 返回登录用户
		return new org.springframework.security.core.userdetails.User(username,password,authorities);
	}
}
